﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using MDF.Logger.Managements;
using MDF.Utilites.Helper;

namespace MDF.Requesting
{

    public class Requester
    {
        private CookieContainer m_ccCookie = new CookieContainer();
        private int m_iRepeat = 2;
        public WebResponse GetData(String _strURL, bool _isUseProxy = false, CookieContainer _ccCookie = null)
        {
            WebResponse res = null;
            for (int i = 0; i < m_iRepeat; i++)
            {
                var uri = new Uri(_strURL);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Add("Accept-Language", "en-us,en;q=0.5");
                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                if (_ccCookie != null)
                    request.CookieContainer = _ccCookie;
                else
                    request.CookieContainer = m_ccCookie;
                if (_isUseProxy)
                    request.Proxy = new WebProxy("186.235.237.58", 8080);
                request.KeepAlive = true;
                request.Referer = _strURL;

                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Cache-Control", "max-age");
                request.Headers.Add("Origin", _strURL);
                request.Method = "GET";
                try
                {
                    res = request.GetResponse();
                    if (res.Headers["Set-Cookie"] != null)
                    {
                        var coki = res.Headers["Set-Cookie"];
                        string[] arrTemp = coki.Split(';');
                        m_ccCookie.SetCookies(uri, coki);
                        LogManager.GetInstance().Info("GET: " + _strURL);
                    }
                    if (res != null)
                        return res;
                    else
                    {
                        LogManager.GetInstance().Warning("Get again " + i);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error("Get respone Get data have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i+1));
                }
            }
            return res;
        }

        //hàm post
        public WebResponse PostData(String _strURL, String _strData, bool _isUseProxy = false, CookieContainer _ccCookie = null)
        {
            WebResponse res = null;
            for (int i = 0; i < m_iRepeat; i++)
            {
                var uri = new Uri(_strURL);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                byte[] data = Encoding.UTF8.GetBytes(_strData);//builder.ToString());

                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0";

                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

                request.Headers.Add("Accept-Language", "en-us,en;q=0.5");

                request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");

                request.KeepAlive = true;
                if (_isUseProxy)
                    request.Proxy = new WebProxy("186.235.237.58", 8080);
                if (_ccCookie != null)
                    request.CookieContainer = _ccCookie;
                else
                    request.CookieContainer = m_ccCookie;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Referer = _strURL;
                request.Headers.Add("Cache-Control", "max-age");
                request.ContentLength = data.Length;

                request.Method = "POST";

                try
                {
                    //thuong xay ra loi tai day (-_-)
                    Stream stream = request.GetRequestStream();
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error("Send post data request have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i+1));
                }
                try
                {
                    res = request.GetResponse();
                    if (res.Headers["Set-Cookie"] != null)
                    {
                        var coki = res.Headers["Set-Cookie"];
                        m_ccCookie.SetCookies(uri, coki);
                    }
                    LogManager.GetInstance().Info("POST: " + _strURL);
                    if(res!=null)
                        return res;
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error("Get respones Post data have a problem!", ex);
                    LogManager.GetInstance().Warning("Get again " + (i+1));
                }
            }
            return res;
        }


        //tra ve ma html tu response
        public String GetHtmlFromResponse(WebResponse response)
        {
            if (response == null)
            {
                LogManager.GetInstance().Error("WebResponse is null");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string temp = "";
            try
            {
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                temp = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Get HTML have a problem!", ex);
                return null;
            }
            finally
            {
                response.Close();
                dataStream.Close();
                reader.Close();
            }
            return temp;
        }
    }
}